package com.wh.minihelp.filter;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.wh.db.jdbc.mysql.BaseJDBCOperations;
import com.wh.lang.LogUtil;
import com.wh.minihelp.filter.impl.FunctionContext;
import com.wh.minihelp.filter.impl.LocalFunctionContext;
import com.wh.minihelp.flower.dao.FlowerDao;
import com.wh.minihelp.flower.domain.SysFlower;

/**
 * 实现代理功能的过滤器
 * 
 * @author washheart@163.com
 */
public class FunctionsFilter implements Filter {
	public final static String Server = "http://paipaizhengli.top";
	public static final String Method = "m";

	private final static IFunctionContext createContext() {
		return new LocalFunctionContext();// 本地调试用
		// return new SAEFunctionContext();// SAE使用
		// return new MaxleapFunctionContext();// MaxLeap网站配置
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		LogUtil.rootLog.info("系统初始化中.....................");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		IFunctionContext fctx = null;
		try {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpSession session = req.getSession();
			// 如果是从微信来的消息，那么每次的session都是新的，如果session中有放东西，需要注意
			ServletContext ctx = session.getServletContext();
			String uri = req.getRequestURI();
			if (LogUtil.rootLog.isDebugEnabled()) {
				LogUtil.rootLog.debug("URI = " + uri);
				Enumeration enu = req.getParameterNames();
				while (enu.hasMoreElements()) {
					String key = (String) enu.nextElement();
					LogUtil.rootLog.debug("\t " + key + "= " + req.getParameter(key));
				}
			}
			uri = req.getServletPath();
			if (uri.startsWith("/res/")) {
				chain.doFilter(request, response);
			} else if (uri.endsWith(".jsp")) {
				chain.doFilter(request, response);
			} else {
				fctx = createContext();
				fctx.initContext(ctx, session, req, (HttpServletResponse) response);
				// if (uri.startsWith("/up")) {// FIXME:delete
				// fctx.forward("/WEB-INF/common/uploadWx.jsp");
				// return;
				// }
				// if (uri.startsWith("/pu")) {// FIXME:delete
				// upload(fctx);
				// }
				String method = fctx.getParameter(FunctionsFilter.Method);
				fctx.forwardModule(uri, method);
			}
		} catch (Throwable e) {
			if (LogUtil.rootLog.isErrorEnabled()) LogUtil.rootLog.error(fctx, e);
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw, true);
			e.printStackTrace(pw);
			pw.close();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.write("<pre>" + sw.toString() + "</pre>");
			out.flush();
			out.close();
		} finally {
			if (fctx != null) fctx.clear();
		}
	}

	private void upload(IFunctionContext fctx) throws ServletException, IOException {
		if (!ServletFileUpload.isMultipartContent(fctx.getRequest())) {
			fctx.error("请选择附件后执行上传操作！");
			return;
		}
		try {
			FileItemFactory factory = new DiskFileItemFactory();// 为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(fctx.getRequest());
			Iterator<FileItem> itr = items.iterator();
			StringBuilder sb = new StringBuilder("请求已接收<br/>");
			System.out.println("age = " + fctx.getParameter("age"));// 这种方式已经获取不到数据了
			FileItem file__ = null;
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				// 检查当前项目是普通表单项目还是上传文件。
				if (item.isFormField()) {// 如果是普通表单项目，显示表单内容。
					String fieldName = item.getFieldName();
					sb.append("----").append(fieldName).append("=").append(item.getString());
				} else {// 如果是上传文件，显示文件名。
					file__ = item;
				}
				sb.append("<br>");
			}
			if (file__ != null) {
				if (file__.getSize() > 0) {
					String realPath = fctx.getTmpPath();
					String fn = file__.getName();
					File uploadFile = new File(realPath, fn);
					file__.write(uploadFile);// 完成上传操作
					sb.append("----").append("uploadFile = " + uploadFile.getCanonicalPath());
					String savedFile = fn;
					String url = fctx.uploadFile(uploadFile.getCanonicalPath(), savedFile);
					sb.append("    ").append("the upload file name = " + savedFile);
					sb.append("\r\n<br/>  ").append("the url==" + url);
					sb.append("\r\n<img src='").append(url).append("'/>");
				} else {
					sb.append("文件大小为0");
				}
			}
			fctx.message(sb.toString());
		} catch (Throwable e) {
			LogUtil.rootLog.error("上传文件出错！", e);
			fctx.error("上传文件出错:" + e.getMessage());
		}
	}

	public void destroy() {}

}